//
//  HUMOpenGLRenderView.swift
//  OpenGLDemo1
//
//  Created by Ming on 2018/9/28.
//  Copyright © 2018年 Ming. All rights reserved.
//

import UIKit

class HUMOpenGLRenderView: UIView {
    var render: HUMOpenGLBaseRender?
    
    private var isAnimating: Bool = false
    private var displayLink: CADisplayLink? = nil
    
    init() {
        super.init(frame: .zero)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    override class var layerClass: AnyClass {
        return CAEAGLLayer.self
    }
    
    private func setup() {
        guard let eaglLayer = self.layer as? CAEAGLLayer else {
            return
        }
        eaglLayer.isOpaque = true
        eaglLayer.contentsScale = UIScreen.main.scale
        eaglLayer.drawableProperties = [kEAGLDrawablePropertyRetainedBacking: false,
                                        kEAGLDrawablePropertyColorFormat: kEAGLColorFormatRGBA8]
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let eaglLayer = self.layer as? CAEAGLLayer {
            _ = render?.resize(from: eaglLayer)
        }
        drawView()
    }
    
    @objc private func drawView() {
        if let render = render {
            render.willRender()
            render.render()
            render.didRender()
        }
    }
}

extension HUMOpenGLRenderView {
    func startAnimation() {
        if !isAnimating {
            if displayLink == nil {
                displayLink = CADisplayLink(target: self, selector: #selector(drawView))
                displayLink?.preferredFramesPerSecond = 0
                displayLink?.add(to: RunLoop.current, forMode: .common)
            }
            isAnimating = true
        }
    }
    func stopAnimation() {
        if isAnimating {
            displayLink?.invalidate()
            displayLink = nil
            isAnimating = false
        }
    }
}
